<?php

namespace addons\activityform\controller;

use app\admin\model\activityform\Fromurl;
use app\admin\model\activityform\Fromurlque;
use app\admin\model\activityform\Fromurldata;
use \think\addons\Controller;
use app\common\exception\UploadException;
use app\common\library\Upload;
use think\App;
use think\Config;
use think\Hook;
use think\Lang;

class Aform extends Controller
{

    protected $layout = '';
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    protected $activityformImgToken = 'activityformImgToken';

    public function _initialize()
    {
        parent::_initialize();
    }

    public function index()
    {
        $sn = $this->request->get("sn");
        $textinfo = Fromurl::get(['sn' => $sn]);

        if (!$textinfo) {
            $textinfo = Fromurl::get(1);
        }
        if ($this->request->isPost()) {
            $post = $this->request->post();

            $result = $this->validate(
                [
                    '__token__' => $post['__token__'],
                    'name' => $post['name'],
                    'phone' => $post['phone']
                ],
                [
                    '__token__' => 'require|token',
                    'name' => 'require',
                    'phone' => 'require'
                ],
                [
                    'name.require' => '姓名为必须',
                    'phone.require' => '手机号为必须'
                ]);
            if (true !== $result) {
                $this->error($result);
            }

            if (!preg_match('^1(3|4|5|6|7|8|9)[0-9]\d{8}$^', $post['phone'])) {
                $this->error(__('手机号码有误'));
            }


            $data['name'] = $this->request->post("name");
            $data['phone'] = $this->request->post("phone");
            $data['weixin'] = empty($post['weixin']) ? '' : $post['weixin'];

            $datas = [];
            $datas['name'] = $data['name'];
            $datas['weixin'] = $data['weixin'];
            $datas['phone'] = $data['phone'];
            $datas['fromurl_id'] = $this->request->post("fromurl_id");
            $datas['createtime'] = time();

            //把自定义数据存入数据库
            $customdata = [];

            $ids = '';
            foreach ($post as $k => $v) {
                if (((substr($k, 0, 5) == 'input') || (substr($k, 0, 5) == 'radio') || (substr($k, 0, 5) == 'check') || (substr($k, 0, 5) == 'image')) && (strlen($k) > 5)) {
                    $tmpid = substr($k, 5);
                    $ids = $ids . $tmpid . ',';

                    if (strpos($k, 'radio') !== false) {
                        $ids = $ids . $v . ',';
                    }

//                    if ((strpos($k, 'check') !== false) || (strpos($k, 'image') !== false)) {
                    if (strpos($k, 'check') !== false) {
                        foreach ($v as $vv) {
                            $ids = $ids . $vv . ',';
                        }
                    }
                }
            }
            $tmpArray = Fromurlque::where('id', 'in', rtrim($ids, ","))->select();
            $tmpArrayTmp = collection($tmpArray)->toArray();

            $tmpArray = [];
            foreach ($tmpArrayTmp as $tmpArrayTmpV) {
                $tmpArray[$tmpArrayTmpV['id']] = $tmpArrayTmpV;
            }

            foreach ($post as $k => $v) {
                if (((substr($k, 0, 5) == 'input') || (substr($k, 0, 5) == 'radio') || (substr($k, 0, 5) == 'check') || (substr($k, 0, 5) == 'image')) && (strlen($k) > 5)) {
                    $tmpid = substr($k, 5);

                    $tmp = [];
                    //一条数据
                    $oneData = $tmpArray[$tmpid];
                    if (strpos($k, 'input') !== false) {
                        $tmp[$oneData['name']] = $v;
                    }

                    if (strpos($k, 'radio') !== false) {
                        $radioData = $tmpArray[$v];
                        $tmp[$oneData['name']] = $radioData['name'];
                    }

                    if (strpos($k, 'check') !== false) {
                        foreach ($v as $vv) {
                            $checkData = $tmpArray[$vv];
                            $tmp[$oneData['name']][] = $checkData['name'];
                        }
                    }

                    if (strpos($k, 'image') !== false) {
                        foreach ($v as $vv) {
                            $tmp[$oneData['name']][] = $vv;
                        }
                    }
                    $customdata[] = $tmp;
                }
            }

            $datas['customdata'] = json_encode($customdata, JSON_UNESCAPED_UNICODE);
            $fromurldata = new Fromurldata();
            $fromurldata->save($datas);


            $this->success(__('提交成功'));
        }


        if (!empty($textinfo['fromurlques_ids'])) {
            $this->view->assign('ques', $this->quesidsToData($textinfo['fromurlques_ids']));
        }

        //该条的数据
        $this->view->assign('textinfo', $textinfo);
        $this->view->assign('ajaxUrl', addon_url('activityform/aform/ajaxIdToData'));
        return $this->view->fetch('../addons/activityform/view/aform/index.html');
    }

    public function ajaxIdToData()
    {
        $head = <<<EOF
<h3 class="smallTitle">demoh3</h3>
EOF;

        $input = <<<EOF
            <ul class="inputBox">
                <li class="radius5 re">
                    <input name="demoInputName" type="text" required class="radius0 ab inputElement"
                           style="left:0rem;border-left:solid 0px #cdd8e0"/>
                </li>
            </ul>
EOF;

        $radio = <<<EOF
<label style="font-size: 0.33rem;line-height: 0.8rem;"><input required value="demoRadioValue" name="demoRadioName" type="demoType"
                                                                          style="width:0.4rem;height:0.4rem;"/>&nbsp;<span
                    style="line-height: 0.4rem;">demoRadioShow</span></label><br>
EOF;

        $image = <<<EOF
<div class="demoImageClassName"></div>
EOF;

        $radioDiv = <<<EOF
            <div id="demoRadioRelateId">
            </div>
EOF;

        $quesArray = $this->quesidsToData($this->request->get("pid"), 'pid');
        $returnHtml = '';

        foreach ($quesArray as $v) {
            $returnHtml .= str_replace('demoh3', $v['name'], $head);

            if (($v['type'] == 'radio') || ($v['type'] == 'checkbox')) {
                foreach ($v['type_desc_relation'] as $key1 => $v1) {
                    if ($v['type'] == 'radio') {
                        $returnHtml .= str_replace('demoRadioShow', $v['type_desc'][$key1], str_replace('demoType', $v['type'], str_replace('demoRadioName', 'radio' . $v['id'], str_replace('demoRadioValue', $v1, $radio))));
                    }

                    if ($v['type'] == 'checkbox') {
                        $returnHtml .= str_replace('required', '', str_replace('demoRadioShow', $v['type_desc'][$key1], str_replace('demoType', $v['type'], str_replace('demoRadioName', 'check' . $v['id'] . '[]', str_replace('demoRadioValue', $v1, $radio)))));
                    }
                }

                $returnHtml .= str_replace('demoRadioRelateId', 'relate' . $v['id'], $radioDiv);
            }
            if ($v['type'] == 'input') {
                $returnHtml .= str_replace('demoInputName', 'input' . $v['id'], $input);
            }

            if ($v['type'] == 'image') {
                $returnHtml .= str_replace('demoImageClassName', 'image-box' . $v['id'], $image);
            }
        }

        return $returnHtml;
    }

    private function quesidsToData($fromurlques_ids, $field = 'id')
    {
        $field = addslashes(sprintf("%s", $field));
        $fromurlques_ids = addslashes(sprintf("%s", $fromurlques_ids));

        $ques = Fromurlque::where($field, 'in', $fromurlques_ids)->orderRaw('field(:field,:fromurlques_ids)', ['field' => $field, 'fromurlques_ids' => $fromurlques_ids])->select();
        $ques = collection($ques)->toArray();

        //应该是找其下面选项的
        //按照id排序
        //应该会用到递归思想
        $ids = '';
        foreach ($ques as $k => $v) {
            if (($v['type'] == 'radio') || ($v['type'] == 'checkbox')) {
                $ids = $ids . $v['id'] . ',';
            }
        }
        $tmpArray = Fromurlque::where('pid', 'in', rtrim($ids, ","))->select();
        $tmpArray = collection($tmpArray)->toArray();

        foreach ($ques as $k => $v) {
            if (($v['type'] == 'radio') || ($v['type'] == 'checkbox')) {
                $ques[$k]['type_desc'] = [];
                $ques[$k]['type_desc_relation'] = [];
                foreach ($tmpArray as $tmpArrayV) {
                    if ($tmpArrayV['pid'] == $v['id']) {
                        $ques[$k]['type_desc'][] = $tmpArrayV['name'];
                        $ques[$k]['type_desc_relation'][] = $tmpArrayV['id'];
                    }
                }
            }
        }

        return $ques;
    }

//上传方法
    public function upload()
    {
// 从 HTTP 请求头中获取 Authorization 字段
        $authorizationHeader = $_SERVER['HTTP_AUTHORIZATION'] ?? '';

// 检查是否有 Authorization 字段，并且是否以 "Bearer " 开头
        if (strpos($authorizationHeader, 'Bearer ') === 0) {
            // 提取 Token
            $token = substr($authorizationHeader, 7);
        }else{
            $token = '';
        }
        // 验证令牌
        $result = $this->validate([$this->activityformImgToken => $token], [
            $this->activityformImgToken => 'require|token' . ':' . $this->activityformImgToken,
        ]);
        if (true !== $result) {
            $this->error($result);
        } else {

            // 载入语言包，避免出现英文错误提示
            Lang::load(APP_PATH . 'api/lang/zh-cn.php');

            // 获取上传配置
            $uploadConfig = Config::get("upload");

            // 兼容云存储上传
            if ($uploadConfig['storage'] != 'local') {
                // 这里可以修改允许上传文件的后缀或修改存储的文件路径，例如只允许上传图片
                set_addon_config($uploadConfig['storage'], ['maxsize' => '10mb', 'mimetype' => 'jpg,png,jpeg,gif'], false);

                // 添加允许上传的行为
                Hook::add('upload_config_checklogin', function () {
                    return true;
                });

                request()->param('isApi', true);
                App::invokeMethod(["\\addons\\{$uploadConfig["storage"]}\\controller\\Index", "upload"], ['isApi' => true]);
        } else {
                // 这里可以修改允许上传文件的后缀或修改存储的文件路径，例如只允许上传图片
                Config::set('upload', array_merge($uploadConfig, ['maxsize' => '10mb', 'mimetype' => 'jpg,png,jpeg,gif']));

                $attachment = null;

                // 获取所有请求中的文件字段
                $files = $this->request->file();

                // 遍历所有文件字段
                foreach ($files as $fieldName => $file) {
                    // 检查字段名是否以 "image" 开头
                    if (strpos($fieldName, 'image') === 0) {
                        $file = $this->request->file($fieldName);
                        break;
                    }
                }

                try {
                    $upload = new Upload($file);
                    $attachment = $upload->upload();
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }

                return json(array('code' => 200, 'src' => cdnurl($attachment->url, true)));
            }
        }
    }

    public function retToken()
    {
        $token = $this->request->token($this->activityformImgToken);

        return json(['token' => $token]);
    }
}